<?php
namespace Common\Logic\Common;

use Common\Base\LogicBase;
use Common\Model\Common\ArticleModel;

class ArticleLogic extends LogicBase
{
    public $m_article;

    public function __construct()
    {
        $this->m_article = new ArticleModel();
    }

    /**
     * 得到数据
     *
     * @param int    $w
     * @param array  $search
     * @param string $fields
     * @param int    $page
     * @param int    $pageSize
     * @param string $by
     *
     * @return array
     */
    public function getCategory($w=3, $search=array(), $fields='*', $page=0, $pageSize=0, $by='')
    {
        return $this->m_article->getCategory($w, $search, $fields, $page, $pageSize, $by);
    }

    /**
     * 得到菜单等级select
     *
     * @param int     $choose 默认选中
     * @param string  $name 名称、ID
     * @param string  $onchange 事件
     * @param boolean $disabled
     *
     * @return string
     */
    public function getCategorySelect($choose=-1, $name='cid', $onchange='', $disabled=false)
    {
        $dis = $disabled ? 'disabled="disabled"' : '';
        $html = '<select name="'.$name.'" id="'.$name.'" onchange="'.$onchange.'" '.$dis.'><option value="-1">--请选择--</option>';
        $choose = intval($choose);
        $datas = $this->getCategory(2, array('st'=>1), 'id,fid,category_name,depth');
        if( ! empty($datas)){
            $datas = list_to_tree($datas, 'id', 'fid');
            floatArray($datas, '_child', $rs);
            $infos = $rs;
            foreach($infos as $v){
                $v['id'] = intval($v['id']);
                $sel = ($v['id'] === $choose) ? 'selected="selected"' : '';
                $html .= '<option value="'.$v['id'].'" '.$sel.'>'.str_repeat('&nbsp;', $v['depth']*6).'┣ '.$v['category_name'].'</option>';
            }
        }
        $html .= '</select>';
        return $html;
    }

    /**
     * 得到分类KV数据结构
     *
     * @return array
     */
    public function getCategoryKV()
    {
        $infos = $this->getCategory(2, array(), 'id,category_name');
        $rs = array();
        if( ! empty($infos)){
            foreach($infos as $v){
                $rs[intval($v['id'])] = $v['category_name'];
            }
        }
        return $rs;
    }

    /**
     * 得到一个分类信息
     *
     * @param int
     *
     * @return array
     */
    public function getCategoryByPK($id = 0)
    {
        $id = intval($id); if($id < 1){ return array(); }
        $info = $this->getCategory(4, array('id'=>$id));
        if(empty($info)){ return array(); }
        $info['id'] = intval($info['id']);
        $info['fid'] = intval($info['fid']);
        $info['depth'] = intval($info['depth']);
        $info['st'] = intval($info['st']);
        $info['px'] = intval($info['px']);
        return $info;
    }

    /**
     * 分类状态（包括下级分类、有关联的文章）
     *
     * @param int $id
     * @param int $st
     *
     * @return boolean
     */
    public function categorySt($id=0, $st=0)
    {
        $id = intval($id);
        if($id < 1){
            $this->setError('参数错误');
            return false;
        }
        $st = intval($st);
        if( ! in_array($st, array(0, 1), true)){
            $this->setError('参数错误');
            return false;
        }

        //检查这个这个分类是否存在
        $ck = $this->getCategoryByPK($id);
        if(empty($ck)){
            $this->setError('没有找到此分类信息');
            return false;
        }

        //待处理分类id数组
        $cid_array[] = $id;

        //取出这个分类的下级分类
        $subs = $this->getCategory(2, array('path_like'=>$id));
        if( ! empty($subs)){
            foreach($subs as $s){
                $cid_array[] = intval($s['id']);
            }
        }

        //更新分类状态 article_category.st
        $this->m_article->editCategory(array('id'=>array('IN', $cid_array)), array('st'=>$st));

        //更新文章的分类状态 article.cid_st
        $this->m_article->editArticle(array('cid'=>array('IN', $cid_array)), array('cid_st'=>$st));

        return true;
    }

    /**
     * 添加分类
     *
     * @param array $post
     *
     * @return mixed
     */
    public function addCategory($post = array())
    {
        $row = array();

        if(isset($post['category_name']) && $post['category_name']!=''){
            $row['category_name'] = $post['category_name'];
        }else{
            $this->setError('请输入分类名称');
            return false;
        }

        if(isset($post['fid']) && intval($post['fid'])>0){
            $row['fid'] = intval($post['fid']);
        }else{
            $row['fid'] = 0;
        }

        //判断是否已经存在
        $ck = $this->getCategory(1, array('fid'=>$row['fid'], 'category_name'=>$row['category_name']));
        if($ck > 0){
            $this->setError('文章分类已经存在');
            return false;
        }

        //处理path,depth字段
        if($row['fid'] === 0){
            $row['path'] = ',0,';
            $row['depth'] = 0;
        }else{
            $info = $this->getCategoryByPK($row['fid']);
            if(empty($info)){
                $this->setError('没有找到上级分类');
                return false;
            }
            $row['path'] = $info['path'].$row['fid'].',';
            $row['depth'] = $info['depth'] + 1;
        }

        $row['px'] = 0;
        $row['st'] = 1;

        $insertID = $this->m_article->addCategory($row);
        if(false === $insertID){
            $this->setError($this->m_article->getError());
            return false;
        }else{
            return $insertID;
        }
    }

    /**
     * 编辑分类
     *
     * @param array $post
     *
     * @return mixed
     */
    public function editCategory($post = array())
    {
        if(isset($post['id']) && intval($post['id'])>0){
            $id = intval($post['id']);
        }else{
            $this->setError('参数错误');
            return false;
        }

        $row = array();

        if(isset($post['category_name']) && $post['category_name']!=''){
            $row['category_name'] = $post['category_name'];
        }else{
            $this->setError('请输入分类名称');
            return false;
        }

        if(isset($post['fid']) && intval($post['fid'])>0){
            $row['fid'] = intval($post['fid']);
        }else{
            $row['fid'] = 0;
        }

        //判断是否已经存在
        $ck = $this->getCategory(1, array('id_neq'=>$id, 'fid'=>$row['fid'], 'category_name'=>$row['category_name']));
        if($ck > 0){
            $this->setError('文章分类已经存在');
            return false;
        }

        //处理path,depth字段
        if($row['fid'] === 0){
            $row['path'] = ',0,';
            $row['depth'] = 0;
        }else{
            $info = $this->getCategoryByPK($row['fid']);
            if(empty($info)){
                $this->setError('没有找到上级分类');
                return false;
            }
            $row['path'] = $info['path'].$row['fid'].',';
            $row['depth'] = $info['depth'] + 1;
        }

        $aff = $this->m_article->editCategory(array('id'=>$id), $row);
        if(false === $aff){
            $this->setError($this->m_article->getError());
            return false;
        }

        //修正下级分类的path、depth
        $this->adjustPath($id);

        return $aff;
    }

    /**
     * 修正path、depth
     *
     * @param int $id
     *
     * @return void
     */
    public function adjustPath($id = 0)
    {
        $id = intval($id); if($id < 0){ $id = 0; }
        $subs = $this->getCategory(2, array('fid'=>$id));
        if(empty($subs)){ return; }
        //先取出当前分类的信息
        $info = $this->getCategoryByPK($id);
        if(empty($info)){ return; }
        foreach($subs as $s){
            $row = array();
            $row['depth'] = $info['depth'] + 1;
            $row['path'] = $info['path'].$id.',';
            $this->m_article->editCategory(array('id'=>$s['id']), $row);
            $this->adjustPath($s['id']);
        }
    }

    /**
     * 删除
     *
     * @param int $id
     *
     * @return mixed
     */
    public function delCategory($id = 0)
    {
        $id = intval($id);
        if($id < 1){
            $this->setError('参数错误');
            return false;
        }
        //检查是否存在下级分类
        $ck = $this->getCategory(4, array('fid'=>$id));
        if( ! empty($ck)){
            $this->setError('存在下级分类，不能删除');
            return false;
        }
        //检查此分类下是否有新闻
        $ck2 = $this->getTableArticle(4, array('cid'=>$id));
        if( ! empty($ck2)){
            $this->setError('分类下有新闻，不能删除');
            return false;
        }
        $aff = $this->m_article->delCategory(array('id'=>$id));
        if(false === $aff){
            $this->setError($this->m_article->getError());
            return false;
        }
        return $aff;
    }

    /**
     * 得到数据
     *
     * @param int    $w
     * @param array  $search
     * @param string $fields
     * @param int    $page
     * @param int    $pageSize
     * @param string $by
     *
     * @return array
     */
    public function getTableArticle($w=3, $search=array(), $fields='*', $page=0, $pageSize=0, $by='')
    {
        return $this->m_article->getTableArticle($w, $search, $fields, $page, $pageSize, $by);
    }

    /**
     * 得到数据
     *
     * @param int    $w
     * @param array  $search
     * @param string $fields
     * @param int    $page
     * @param int    $pageSize
     * @param string $by
     *
     * @return array
     */
    public function getArticle($w=3, $search=array(), $fields='a.*,b.category_name', $page=0, $pageSize=0, $by='')
    {
        return $this->m_article->getArticle($w, $search, $fields, $page, $pageSize, $by);
    }

    /**
     * 得到一篇文章
     *
     * @param int $id
     *
     * @return boolean
     */
    public function getArticleByPK($id = 0)
    {
        $id = intval($id);
        if(empty($id)){ return array(); }
        $info = $this->getArticle(4, array('id'=>$id));
        if(empty($info)){ return array(); }
        $info['id'] = intval($info['id']);
        $info['cid'] = intval($info['cid']);
        $info['add_ts'] = intval($info['add_ts']);
        $info['st'] = intval($info['st']);
        $info['cid_st'] = intval($info['cid_st']);
        $info['admin_id'] = intval($info['admin_id']);
        $info['px'] = intval($info['px']);
        $info['content'] = Out($info['content']);
        return $info;
    }

    /**
     * 新增文章
     *
     * @param array $post
     *
     * @return boolean
     */
    public function addArticle($post = array())
    {
        $row = array();

        if(isset($post['cid']) && intval($post['cid'])>0){
            $row['cid'] = intval($post['cid']);
        }else{
            $row['cid'] = 0;
        }

        if(isset($post['title']) && $post['title']!=''){
            $row['title'] = $post['title'];
        }else{
            $this->setError('文章标题必须填写');
            return false;
        }

        if(isset($post['author']) && $post['author']!=''){
            $row['author'] = $post['author'];
        }else{
            $this->setError('文章来源必须填写');
            return false;
        }

        if(isset($post['content']) && $post['content']!=''){
            $row['content'] = $post['content'];
        }else{
            $this->setError('文章内容必须填写');
            return false;
        }

        $row['add_ts'] = NOW_TIME;
        $row['st'] = 1;
        $row['cid_st'] = 1;
        $row['admin_id'] = 0;
        $row['px'] = 0;

        $insertID = $this->m_article->addArticle($row);
        if(false === $insertID){
            $this->setError($this->m_article->getError());
            return false;
        }

        return $insertID;
    }

    /**
     * 编辑文章
     *
     * @param array $post
     *
     * @return boolean
     */
    public function editArticle($post = array())
    {
        if(isset($post['id']) && intval($post['id'])>0){
            $id = intval($post['id']);
        }else{
            $this->setError('参数错误');
            return false;
        }

        $row = array();

        if(isset($post['cid']) && intval($post['cid'])>0){
            $row['cid'] = intval($post['cid']);
        }else{
            $row['cid'] = 0;
        }

        if(isset($post['title']) && $post['title']!=''){
            $row['title'] = $post['title'];
        }else{
            $this->setError('文章标题必须填写');
            return false;
        }

        if(isset($post['author']) && $post['author']!=''){
            $row['author'] = $post['author'];
        }else{
            $this->setError('文章来源必须填写');
            return false;
        }

        if(isset($post['content']) && $post['content']!=''){
            $row['content'] = $post['content'];
        }else{
            $this->setError('文章内容必须填写');
            return false;
        }

        $aff = $this->m_article->editArticle(array('id'=>$id), $row);
        if(false === $aff){
            $this->setError($this->m_article->getError());
            return false;
        }

        return $aff;
    }
}